package com.neuronbit.businessflow.intellij.editor.codec;

import com.mxgraph.io.mxObjectCodec;
import com.neuronbit.businessflow.intellij.model.ParamValue;
import com.neuronbit.businessflow.intellij.model.Return;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * The type Return codec.
 */
public class ReturnCodec extends mxObjectCodec {
    /**
     * Instantiates a new Return codec.
     */
    public ReturnCodec() {
        super(new Return());
    }

    @Override
    protected Object getFieldValue(Object obj, String fieldName) {
        Object fieldValue = super.getFieldValue(obj, fieldName);
        if (fieldName.equals("value") && fieldValue != null) {
            return fieldValue.toString();
        }
        return fieldValue;
    }

    @Override
    protected void setFieldValue(Object obj, String fieldName, Object value) {
        if (fieldName.equals("value") && value != null) {
            String vs = value.toString();
            Set<ParamValue> v = new HashSet<>();
            if (vs.contains(",")) {
                String[] split = vs.split(",");

                for (String s : split) {
                    if (StringUtils.isNoneBlank(s)) {
                        v.add(new ParamValue(s));
                    }
                }
            } else {
                v.add(new ParamValue(vs));
            }
            super.setFieldValue(obj, fieldName, v);
        } else {
            super.setFieldValue(obj, fieldName, value);
        }
    }
}
